package com.rongke.web.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.service.*;
import com.rongke.utils.ArrayUtils;
import com.rongke.utils.StringUtil;
import com.rongke.utils.ThreadPool;
import com.rongke.web.gubo.RoyaltyApi;
import com.rongke.web.gubo.Txgupiao;
import com.rongke.web.yiyuan.YiyuanApi;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import static com.rongke.web.gubo.RoyaltyApi.getPrecent;

/**
 * @ShareController
 * @股票Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/share")
@Transactional
@CrossOrigin
public class ShareController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private ShareService shareService;
    @Autowired
    private SysParamsService sysParamsService;
    @Autowired
    private ShareNeedService shareNeedService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserCollectShareService userCollectShareService;


    /**
     * @添加股票
     * @param share
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addShare(@RequestBody Share share){
        log.debug("添加股票");
        shareService.insert(share);
        return JsonResp.ok(share);
    }

    /**
     * @修改股票
     * @param share
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateShare(@RequestBody Share share){
        log.debug("修改股票");
        shareService.updateById(share);
        return JsonResp.ok(share);
    }
    /**
     * @根据id查找股票
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectShare(Long id){
        log.debug("查找股票");
        Share share = shareService.selectById(id);
        return JsonResp.ok(share);
    }


    /**
     * @修改股票
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/test", method = RequestMethod.GET)
    public JsonResp test(){
        log.debug("修改股票");
        EntityWrapper<Share> ew = new EntityWrapper<>();
        ew.eq("status",2);
        List<Share> shareList = shareService.selectList(ew);
        List<ShareNeed> shareNeedList = new ArrayList<>();
        for(Share s:shareList){
            ShareNeed shareNeed = new ShareNeed();
            shareNeed.setShareCode(s.getShareType()+s.getShareCode());
            shareNeedList.add(shareNeed);
        }
        shareNeedService.deleteSomeShareNeed(shareNeedList);
        return JsonResp.ok();
    }
    /**
     * @调用第三方接口存储股票列表信息
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/saveAllShare", method = RequestMethod.GET)
    public JsonResp saveAllShare(){
        log.debug("调用第三方接口存储股票列表信息");
        List<ShareNeed> shareNeedList = new ArrayList<>();
        //由于第三方数据分页只能循环调用
        for (int i=1;i<100;i++){
            Thread thread = new Thread();
            try {
                thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            JSONObject result = YiyuanApi.selectAllShare(String.valueOf(i),"sz");
            if(result.get("showapi_res_code").toString().equals("0")){
                if(result.getJSONObject("showapi_res_body").getString("allPages").equals("0")){
                    //没有数据之后跳出
                    break;
                }
                JSONArray shareList = result.getJSONObject("showapi_res_body").getJSONArray("contentlist");
                List<Share> list = new ArrayList<>();
                for(int j=0;j<shareList.size();j++){
                    //出去含有ST的股票
                    if(!shareList.getJSONObject(j).getString("name").contains("ST")){
                        Share share = new Share();
                        share.setShareCode(shareList.getJSONObject(j).getString("code"));
                        share.setShareName(shareList.getJSONObject(j).getString("name"));
                        share.setShareType(shareList.getJSONObject(j).getString("market"));
                        share.setState(Integer.parseInt(shareList.getJSONObject(j).getString("state")));
                        share.setType(1);
                        share.setGmtDatetime(new Date());
                        list.add(share);
                        //默认启用，第三方接口必须加前缀
                        ShareNeed shareNeed = new ShareNeed();
                        shareNeed.setShareCode(shareList.getJSONObject(j).getString("market")+shareList.getJSONObject(j).getString("code"));
                        shareNeedList.add(shareNeed);
                    }

                }
                shareService.insertSome(list);
            }else{
                return JsonResp.fa(result.get("showapi_res_error").toString());
            }
        }
        shareNeedService.insertSome(shareNeedList);

        return JsonResp.ok();
    }


    /**
     * @后台分页查询股票
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectSharePage", method = RequestMethod.GET)
    public JsonResp selectSharePage(Page page, String search,Integer status){
        log.debug("后台分页查询股票");
        page.setSize(20);
        EntityWrapper<Share> ew = new EntityWrapper<>();
        if(status!=0){
            ew.eq("status",status);
        }
        if(!StringUtil.isEmpty(search)){
            ew.like("share_name",search);
            ew.or("");
            ew.like("share_code",search);
            //ew.like("share_name",search);
        }
        ew.notIn("status",3);
        Page list = shareService.selectPage(page,ew);
        return JsonResp.ok(list);
    }

    /**
     * @查询一个股票的所有权利金
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectShareAllRoyalty", method = RequestMethod.GET)
    public JsonResp selectShareAllRoyalty(String code){
        log.debug("查询一个股票的所有权利金");
        //获取第三方接口所需token
        EntityWrapper<SysParams> ew = new EntityWrapper<>();
        ew.eq("sys_key","royaltyToken");
        SysParams sysParams = sysParamsService.selectOne(ew);
        if(sysParams==null){
            return JsonResp.fa("无token参数，联系技术！");
        }
        Map map = new HashMap();
        try {
            //调用四个周期第三方
            JSONObject result = getPrecent(code,"5",sysParams.getSysValue());
            if(result.getString("code").equals("000000")){
                String onePrecent = result.getJSONObject("data").getString("premium_rate");
                map.put("onePrecent",onePrecent);
            }else{
                return JsonResp.fa(result.getString("msg"));
            }
            String twoPrecent = getPrecent(code,"10",sysParams.getSysValue()).getJSONObject("data").getString("premium_rate");
            String threePrecent = getPrecent(code,"20",sysParams.getSysValue()).getJSONObject("data").getString("premium_rate");
            String fourPrecent = getPrecent(code,"40",sysParams.getSysValue()).getJSONObject("data").getString("premium_rate");
            map.put("twoPrecent",twoPrecent);
            map.put("threePrecent",threePrecent);
            map.put("fourPrecent",fourPrecent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JsonResp.ok(map);
    }


    /**
     * @后台操作股票
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/operateShare", method = RequestMethod.GET)
    public JsonResp selectSharePage(Long id,Integer type){
        log.debug("后台操作股票");
        Share share = shareService.selectById(id);
        EntityWrapper<ShareNeed> ew = new EntityWrapper<>();
        ew.eq("share_code",share.getShareCode());
        ShareNeed shareNeed = shareNeedService.selectOne(ew);
        if(type.equals(1)){
            //删除
            share.setStatus(3);
            shareNeedService.deleteById(shareNeed);
        }else if(type.equals(2)){
            //禁用
            share.setStatus(2);
            shareNeedService.deleteById(shareNeed);
        }else if(type.equals(3)){
            //启用
            share.setStatus(1);
        }
        shareService.updateById(share);
        return JsonResp.ok();
    }

    /**
     * @禁用所有无期权股票
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/stopSomeShare", method = RequestMethod.GET)
    public JsonResp stopSomeShare(){
        log.debug("禁用所有无期权股票");
        //找到所有启用中的股票
        EntityWrapper<Share> ewShare = new EntityWrapper<>();
        ewShare.eq("status",1);
        List<Share> shareList = shareService.selectList(ewShare);
        List<Share> needStopShares = new ArrayList<>();
        List<ShareNeed> shareCodeList = new ArrayList<>();
        for(Share s:shareList){
            //获取第三方接口所需token
            EntityWrapper<SysParams> ewSys = new EntityWrapper<>();
            ewSys.eq("sys_key","royaltyToken");
            SysParams sysParams = sysParamsService.selectOne(ewSys);
            try {
                JSONObject result = RoyaltyApi.getPrecent(s.getShareCode(),"5",sysParams.getSysValue());
                if(result.getString("code").equals("000300")||result.getString("code").equals("000301")||result.getString("code").equals("000302")){
                    s.setStatus(2);
                    needStopShares.add(s);
                    ShareNeed shareNeed = new ShareNeed();
                    shareNeed.setShareCode(s.getShareCode());
                    shareCodeList.add(shareNeed);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        shareService.updateAll(needStopShares);
        //删除share_need中数据，前端不展示
        shareNeedService.deleteSomeShareNeed(shareCodeList);
        return JsonResp.ok();
    }

    /**
     * @存储启用中股票权利金
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/updateRoyalty", method = RequestMethod.GET)
    public JsonResp updateRoyalty(){
        log.debug("存储启用中股票权利金");
        //找到所有启用中的股票
        EntityWrapper<Share> ewShare = new EntityWrapper<>();
        ewShare.eq("status",1);
        final List<Share> shareList = shareService.selectList(ewShare);
        List<List<Share>> parts= ArrayUtils.averageAssign(shareList,10);
        //获取第三方接口所需token
        EntityWrapper<SysParams> ewSys = new EntityWrapper<>();
        ewSys.eq("sys_key","royaltyToken");
        final SysParams sysParams = sysParamsService.selectOne(ewSys);
        List<Future<List<Share>>> futureList = new ArrayList<>();
        final String token = sysParams.getSysValue();
        for(int i=0;i<parts.size();i++){
            final List<Share> part = parts.get(i);
            //开线程
            ThreadPoolExecutor executor = ThreadPool.getThreadPoolExecutor();
            Callable<List<Share>> callable = new Callable() {
                @Override
                public Object call() throws Exception {
                    for(Share s:part){
                        JSONObject result1 = null;
                        try {
                             result1 = RoyaltyApi.getPrecent(s.getShareCode(),"5",token);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(result1.getString("code").equals("000000")){
                            String onePrecent = result1.getJSONObject("data").getString("premium_rate");
                            s.setRoyalty(onePrecent);
                        }else{
                            //没有权利金直接删除
                        }
                        JSONObject result2 = null;
                        try {
                            result2 = RoyaltyApi.getPrecent(s.getShareCode(),"10",token);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(result2.getString("code").equals("000000")){
                            String onePrecent = result2.getJSONObject("data").getString("premium_rate");
                            s.setRoyalty(s.getRoyalty()+";"+onePrecent);
                        }else{
                            //没有权利金直接删除
                        }
                        JSONObject result3 = null;
                        try {
                            result3 = RoyaltyApi.getPrecent(s.getShareCode(),"20",token);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(result3.getString("code").equals("000000")){
                            String onePrecent = result3.getJSONObject("data").getString("premium_rate");
                            s.setRoyalty(s.getRoyalty()+";"+onePrecent);
                        }else{
                            //没有权利金直接删除
                        }
                        JSONObject result4 = null;
                        try {
                            result4 = RoyaltyApi.getPrecent(s.getShareCode(),"40",token);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(result4.getString("code").equals("000000")){
                            String onePrecent = result4.getJSONObject("data").getString("premium_rate");
                            s.setRoyalty(s.getRoyalty()+";"+onePrecent);
                        }else{
                            //没有权利金直接删除
                        }
                    }
                    return part;
                }
            };
            Future<List<Share>> future = executor.submit(callable);
            futureList.add(future);
        }
        List<Share> newList = new ArrayList<>();
        for (Future<List<Share>> future : futureList) {
            try {
                newList.addAll(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        shareService.updateAll(newList);


     /*   //获取第三方接口所需token
        EntityWrapper<SysParams> ewSys = new EntityWrapper<>();
        ewSys.eq("sys_key","royaltyToken");
        SysParams sysParams = sysParamsService.selectOne(ewSys);
        for(Share s:shareList){
                    Thread thread = new Thread();
                    try {
                        thread.sleep(100L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        JSONObject result = RoyaltyApi.getPrecent(s.getShareCode(),"5",sysParams.getSysValue());
                        if(result.getString("code").equals("000000")){
                            String onePrecent = result.getJSONObject("data").getString("premium_rate");
                            s.setRoyalty(onePrecent);
                        }else{
                            //没有权利金直接删除
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
        /*shareService.updateAll(shareList);*/
        return JsonResp.ok();
    }



    /**
     * @前台股票列表
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/shareAppList", method = RequestMethod.GET)
    public JsonResp shareAppList(Integer current){
        log.debug("前台股票列表");
        //讲股票码拼接
        Map map = new HashMap();
        map.put("pageNo",(current-1)*10);
        map.put("pageSize",20);
        List<ShareNeed> shareNeedList = shareNeedService.selectCode(map);
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i<shareNeedList.size();i++){
            if(i!=0){
                sb.append(",");
            }
            sb.append(shareNeedList.get(i).getShareCode());
        }
        //查询第三方接口
        String result = Txgupiao.getShareMsg(sb.toString());
        String[] shareObj = result.split(";");
        List<ShareFake> shareFakeList = new ArrayList<>();
        for(int i=0;i<shareObj.length;i++){
            String[] msgArray = shareObj[i].split("~");
            ShareFake shareFake = new ShareFake();
            shareFake.setShareCode(msgArray[2]);
            shareFake.setChgPerices(msgArray[31]);
            shareFake.setChgPrecent(msgArray[32]);
            shareFake.setNowPerices(msgArray[3]);
            shareFake.setShareName(msgArray[1]);
            shareFake.setTodayPerices(msgArray[5]);
            shareFake.setShareType(msgArray[0].substring(2,4));
            shareFakeList.add(shareFake);
        }
        return JsonResp.ok(shareFakeList);
    }

    /**
     * @大盘股
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/bigShare", method = RequestMethod.GET)
    public JsonResp bigShare(){
        log.debug("大盘股");
        //查询第三方接口
        String result = Txgupiao.getShareMsg("sh000001,sz399001,sh000300");
        String[] shareObj = result.split(";");
        List<ShareFake> shareFakeList = new ArrayList<>();
        for(int i=0;i<shareObj.length;i++){
            String[] msgArray = shareObj[i].split("~");
            ShareFake shareFake = new ShareFake();
            shareFake.setShareCode(msgArray[2]);
            shareFake.setChgPerices(msgArray[31]);
            shareFake.setChgPrecent(msgArray[32]);
            shareFake.setNowPerices(msgArray[3]);
            shareFake.setShareName(msgArray[1]);
            shareFake.setTodayPerices(msgArray[5]);
            shareFakeList.add(shareFake);
        }
        return JsonResp.ok(shareFakeList);
    }


    /**
     * @股票单个查询
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOneShare", method = RequestMethod.GET)
    public JsonResp bigShare(String code,String shareType){
        log.debug("股票单个查询");
        //查询第三方接口
        String result = Txgupiao.getShareMsg(shareType+code);
        String[] msgArray = result.split("~");
        ShareFake shareFake = new ShareFake();
        shareFake.setShareCode(msgArray[2]);
        shareFake.setChgPerices(msgArray[31]);
        shareFake.setChgPrecent(msgArray[32]);
        shareFake.setNowPerices(msgArray[3]);
        shareFake.setShareName(msgArray[1]);
        shareFake.setTodayPerices(msgArray[5]);
        return JsonResp.ok(shareFake);
    }

    

    /**
     * @前台刷新已有股票列表
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/refreshStockDataList", method = RequestMethod.GET)
    public JsonResp refreshStockDataList(Integer size){
        log.debug("前台刷新已有股票列表");
        //讲股票码拼接
        Map map = new HashMap();
        map.put("pageNo",0);
        map.put("pageSize",size);
        List<ShareNeed> shareNeedList = shareNeedService.selectCode(map);
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i<shareNeedList.size();i++){
            if(i!=0){
                sb.append(",");
            }
            sb.append(shareNeedList.get(i).getShareCode());
        }
        //查询第三方接口
        String result = Txgupiao.getShareMsg(sb.toString());
        String[] shareObj = result.split(";");
        List<ShareFake> shareFakeList = new ArrayList<>();
        for(int i=0;i<shareObj.length;i++){
            String[] msgArray = shareObj[i].split("~");
            ShareFake shareFake = new ShareFake();
            shareFake.setShareCode(msgArray[2]);
            shareFake.setChgPerices(msgArray[31]);
            shareFake.setChgPrecent(msgArray[32]);
            shareFake.setNowPerices(msgArray[3]);
            shareFake.setShareName(msgArray[1]);
            shareFake.setTodayPerices(msgArray[5]);
            shareFakeList.add(shareFake);
        }
        return JsonResp.ok(shareFakeList);
    }

    /**
     * @模糊搜索
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/shareLikeSearch", method = RequestMethod.GET)
    public JsonResp shareLikeSearch(String search){
        log.debug("模糊搜索");
        List<Share> shareList = shareService.selectLikeShare(search);
        return JsonResp.ok(shareList);
    }

    /**
     * @加入或删除自选
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/addCollect", method = RequestMethod.GET)
    public JsonResp addCollect(String code,String shareType,Integer type){
        log.debug("加入或删除自选");
        User user = userService.findLoginUser();
        EntityWrapper<UserCollectShare> ew = new EntityWrapper<>();
        ew.eq("share_code",shareType+code);
        ew.eq("user_id",user.getId());
        UserCollectShare ucs = userCollectShareService.selectOne(ew);
        if(type==1){
            if(ucs !=null){
                return JsonResp.fa("您已经添加过，不能重复添加");
            }
            UserCollectShare userCollectShare = new UserCollectShare();
            userCollectShare.setShareCode(shareType+code);
            userCollectShare.setUserId(user.getId());
            userCollectShareService.insert(userCollectShare);
        }else if(type==0){
            if(ucs !=null){
                userCollectShareService.deleteById(ucs);
            }
        }
        return JsonResp.ok();
    }


    /**
     * @自选股票
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/collectShareList", method = RequestMethod.GET)
    public JsonResp collectShareList(){
        log.debug("模糊搜索");
        User user = userService.findLoginUser();
        EntityWrapper<UserCollectShare> ew = new EntityWrapper<>();
        ew.eq("user_id",user.getId());
        List<UserCollectShare> list = userCollectShareService.selectList(ew);
        if(list.size()!=0){
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<list.size();i++ ){
                if(i!=0){
                    sb.append(",");
                }
                sb.append(list.get(i).getShareCode());
            }
            //查询第三方接口
            String result = Txgupiao.getShareMsg(sb.toString());
            String[] shareObj = result.split(";");
            List<ShareFake> shareFakeList = new ArrayList<>();
            for(int i=0;i<shareObj.length;i++){
                String[] msgArray = shareObj[i].split("~");
                ShareFake shareFake = new ShareFake();
                shareFake.setShareCode(msgArray[2]);
                shareFake.setChgPerices(msgArray[31]);
                shareFake.setChgPrecent(msgArray[32]);
                shareFake.setNowPerices(msgArray[3]);
                shareFake.setShareName(msgArray[1]);
                shareFake.setTodayPerices(msgArray[5]);
                shareFake.setShareType(msgArray[0].substring(2,4));
                shareFakeList.add(shareFake);
            }
            return JsonResp.ok(shareFakeList);
        }
        return JsonResp.ok();
    }

/*    *//**
     * @订单出仓
     * @param
     * @return 返回值JsonResp
     *//*
    @RequestMapping(value="/order", method = RequestMethod.GET)
    public JsonResp addCollect(String code,String shareType,Integer type){
        log.debug("加入或删除自选");
        if(type==1){
            UserCollectShare userCollectShare = new UserCollectShare();
            userCollectShare.setShareCode(shareType+code);
            User user = userService.findLoginUser();
            userCollectShare.setUserId(user.getId());
            userCollectShareService.insert(userCollectShare);
        }else if(type==0){
            EntityWrapper<UserCollectShare> ew = new EntityWrapper<>();
            ew.eq("share_code",shareType+code);
            UserCollectShare userCollectShare = userCollectShareService.selectOne(ew);
            userCollectShareService.deleteById(userCollectShare);
        }
        return JsonResp.ok();
    }*/













}
